//
//  DateUtil.swift
//  ComponentUtils
//
//  Created by wrs on 2018/7/18.
//  Copyright © 2018年 wrs. All rights reserved.
//

import Foundation
public let DATE_TIME_FORMAT: String = "yyyy-MM-dd HH:mm:ss"
public let DATE_FORMAT: String = "yyyy-MM-dd"
public let TIME_FORMAT: String = "HH:mm:ss"

fileprivate let dateFormatter: DateFormatter = DateFormatter()

public func getDateStr(date: Date, format: String) -> String {
    let str = getDateStr(date: date, format: format, dateFormatter: dateFormatter)
    return str
}

public func getDate(dateStr: String, format: String) -> Date? {
    dateFormatter.dateFormat = format
  let date =  dateFormatter.date(from: dateStr)
    return date
}

public func getDateStr(dateStr: String, sourceFormat: String, targetFormat: String) -> String {
    if let date = getDate(dateStr: dateStr, format: sourceFormat) {
        let str = getDateStr(date: date, format: targetFormat)
        return str
    } else {
        return ""
    }
}

public func getDateStr(date: Date, format: String, dateFormatter: DateFormatter) -> String {
    dateFormatter.dateFormat = format
    let str = dateFormatter.string(from: date)
    return str
}

public func getDayNumForMonthWithDate(date: Date) -> Int? {
    let calendar = Calendar.current
   let range = calendar.range(of: Calendar.Component.day, in: Calendar.Component.month, for: date)
    return range?.upperBound
}

public func getDate(date: Date, afterDays: Int) -> Date? {
    var dateComponents = DateComponents()
    dateComponents.day = afterDays
   let resultDate = Calendar.current.date(byAdding: dateComponents, to: date)
    return resultDate
}

public func isSameDay(date: Date, otherDate: Date) -> Bool {
    let calendar = Calendar.current
    let flag = Set<Calendar.Component>(arrayLiteral: Calendar.Component.year,  Calendar.Component.month,  Calendar.Component.day)
    let comp1 = calendar.dateComponents(flag, from: date)
    let comp2 = calendar.dateComponents(flag, from: otherDate)
    let result = (comp1.day == comp2.day) && (comp1.month == comp2.month) && (comp1.year == comp2.year)
    return result
}

//  *
//周日   周一  周二  周三  周四  周五  周六
//1      2    3    4     5    6    7
public func getWeekDay(date: Date) -> Int {
    let calendar = Calendar.current
    let flag = Set<Calendar.Component>(arrayLiteral: Calendar.Component.weekday)
    let comp = calendar.dateComponents(flag, from: date)
    var result: Int = 0
    if let day = comp.weekday {
        result = day
    }
    return result
}

